package manager

import android.content.Context
import android.telephony.PhoneStateListener
import android.telephony.SignalStrength
import android.telephony.TelephonyManager
import app.AppContext
import event.StatusChangedEvent
import ext.log
import mvc.model.Status
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject

object StatusManager : PhoneStateListener(), Runnable {

    private val mTelephonyManager = AppContext.getSystemService(
        Context.TELEPHONY_SERVICE
    ) as TelephonyManager

    var Signal = 0
    var StatusCount = 0

    var status = Status.statusWithNormal()

    init {
        mTelephonyManager.listen(this, LISTEN_SIGNAL_STRENGTHS)
    }

    fun refresh(byteArray: ByteArray) {

        StatusCount++

        val s = Status(byteArray) // 新状态

        EventBus.getDefault().post(StatusChangedEvent(s))

        if (s != status) {
            if (status.isFridgeOpen() && (!s.isFridgeOpen())) { // 开 => 关闭
                Status.appendTimeOut = Status.APPEND_TIME_OUT
            }
            status = s
            AsyncTask.post(this)
            EventBus.getDefault().post(StatusChangedEvent(status, true))
            return
        }
        status = s
    }

    fun toJsonWith3(
        value: String = String.format(
            "%.1f/%d", status.fridgeTempValue(),
            status.ovenTempValue
        )
    ): String {
        val mcuVersion = String.format("%04x", AppManager.McuSoftVersion)
        val json = JSONObject()
        json.put("macAddr", AppManager.MacAddress)
        json.put("houseTemperature", value)
        json.put("lowVersion", mcuVersion)
        json.put("clientVersion", AppManager.Version)
        json.put("cpu", CpuManager.cpuInfo)
        json.put("signStrength", Signal)
        json.put("ram", CpuManager.memoryInfo)
        return json.toString()
    }

    override fun run() {
        try {
            val content = status.toJsonWithDly()
            log(content, "即使上传状态")
            val ret = NetworkManager.updateDlyStatusToServer(content)
            log("---$ret", "即使上传状态返回")
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onSignalStrengthsChanged(signalStrength: SignalStrength) {
        val tmp = signalStrength.toString()
        val parts = tmp.split(" ")
        val dbm = parts[1].toInt() * 2 - 113
        if (mTelephonyManager.networkType == TelephonyManager.NETWORK_TYPE_LTE) {
            if (dbm > 0) {
                Signal = 0
            } else if (dbm > -60) {
                Signal = 4
            } else if (dbm > -75) {
                Signal = 3
            } else if (dbm > -80) {
                Signal = 2
            } else if (dbm > -90) {
                Signal = 1
            }
        } else {
            Signal = 0
        }
        super.onSignalStrengthsChanged(signalStrength)
    }
}